from django.http import JsonResponse
from django.shortcuts import render
from django.utils.baseconv import base64
from django.utils.decorators import method_decorator
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from common.custom_exceptions import decorator_exception
from common.models import MusicInfo
from common.views import BaseListView, AuthTemplateView, get_obj, AuthShopAPIView, AuthMobileTemplateView
from order.models import OrderProduct
from product.models import Product, ProductType
from product.serializers import ProductSerializer


class ProductListView(BaseListView):
    """商品列表"""
    template_name = 'product/list.html'
    model = Product
    context_object_name = "product_list"

    def get_queryset(self):
        self.keyword = self.request.GET.get('keyword', '')
        if self.keyword:
            self.keyword = self.keyword.replace('-', '+').replace('_', '/')
            self.keyword = (base64.decodestring(self.keyword)).strip()
        return Product.objects.filter(title__contains=self.keyword, shop=self.shop, status=Product.STATUS_VALID)

    def get_context_data(self, **kwargs):
        kwargs['secure'] = self.request.is_secure()
        return super(ProductListView, self).get_context_data(**kwargs)


class ProductAddView(AuthTemplateView):
    """新建商品"""
    template_name = 'product/add.html'
    serializer_class = ProductSerializer

    def get_context_data(self, **kwargs):
        kwargs['secure'] = self.request.is_secure()
        kwargs['musics'] = MusicInfo.objects.filter(status=MusicInfo.STATUS_VALID)
        kwargs['types'] = ProductType.objects.filter(shop=self.shop, status=ProductType.STATUS_VALID)

        return super(ProductAddView, self).get_context_data(**kwargs)

    def post(self, request, *args, **kwargs):
        serializer = ProductSerializer(data=request.POST)
        if serializer.is_valid():
            serializer.save(shop_id=kwargs['shop_id'], status=Product.STATUS_VALID)
            return JsonResponse({'status': 0, 'detail': 'success'})
        else:
            return JsonResponse({'status': 1, 'detail': '商品添加失败！', 'errors': serializer.errors})


class ProductEditView(AuthTemplateView):
    """新建商品"""
    template_name = 'product/edit.html'
    serializer_class = ProductSerializer

    def get_context_data(self, **kwargs):
        kwargs['secure'] = self.request.is_secure()
        kwargs['product'] = get_obj(Product, id=self.request.GET.get('id'))
        return super(ProductEditView, self).get_context_data(**kwargs)

    def post(self, request, *args, **kwargs):
        product = get_obj(Product, id=request.POST.get('id'))
        serializer = ProductSerializer(product, data=request.POST)
        if serializer.is_valid():
            serializer.save(status=Product.STATUS_VALID)
            return JsonResponse({'status': 0, 'detail': 'success'})
        else:
            return JsonResponse({'status': 1, 'detail': serializer.errors, 'errors': serializer.errors})


class ProductShelveView(AuthShopAPIView):
    permission_classes = (IsAuthenticated,)

    def post(self, request, *args, **kwargs):
        if not {'title', 'id'}.issubset(request.data):
            return Response({'status': 1, 'detail': '参数错误'})
        product = get_obj(Product, id=request.data.get('id'), status=Product.STATUS_VALID)
        if not product:
            return Response({'status': 1, 'detail': '商品不存在！'})
        product.shelve = not product.shelve
        product.save()
        return Response({'status': 0, 'detail': 'success'})


class ProductDeleteView(AuthShopAPIView):
    permission_classes = (IsAuthenticated,)

    def post(self, request, *args, **kwargs):
        """
        商品删除API
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        if not {'items'}.issubset(request.data):
            return Response({'status': 1, 'detail': '参数错误'})
        id_list = request.data.get("items").split(',')
        product_list = Product.objects.filter(status=Product.STATUS_VALID, id__in=id_list)
        if not product_list:
            return Response({'status': 1, 'detail': '商品列表不存在！'})
        for product in product_list:
            product.status = Product.STATUS_INVALID
            product.save()
        return Response({'status': 0, 'detail': 'success'})


class ProductOrderListView(BaseListView):
    """商品列表"""
    template_name = 'product/order_list.html'
    model = Product
    context_object_name = "order_list"

    def get_queryset(self):
        self.keyword = self.request.GET.get('keyword', '')
        # 测试错误邮件
        # raise Exception('测似错误邮件')
        if self.keyword:
            self.keyword = self.keyword.replace('-', '+').replace('_', '/')
            self.keyword = (base64.decodestring(self.keyword)).strip()
        return OrderProduct.objects.filter(name__contains=self.keyword, info__shop=self.shop,
                                           status=OrderProduct.STATUS_VALID)

    def get_context_data(self, **kwargs):
        kwargs['secure'] = self.request.is_secure()
        return super(ProductOrderListView, self).get_context_data(**kwargs)


class ProductMobileListView(AuthMobileTemplateView):
    template_name = 'product/mobile_list.html'

    def get_context_data(self, **kwargs):
        kwargs['product_list'] = Product.objects.filter(status=Product.STATUS_VALID, shelve=True, shop=self.shop)
        return super(ProductMobileListView, self).get_context_data(**kwargs)


class ProductDetailView(AuthMobileTemplateView):
    template_name = 'product/detail_view.html'

    def get_context_data(self, **kwargs):
        kwargs['product'] = self.product
        return super(ProductDetailView, self).get_context_data(**kwargs)

    def get(self, request, *args, **kwargs):
        self.product = get_obj(Product, id=kwargs['product_id'], status=Product.STATUS_VALID)
        if not self.product:
            return render(request, 'mobile/message.html', {'message': '商品不存在，请退出重试！'})
        if not self.product.shelve:
            return render(request, 'mobile/message.html', {'message': '活动未上架！'})
        return super(ProductDetailView, self).get(self, request, *args, **kwargs)

    @method_decorator(decorator_exception)
    def post(self, request, *args, **kwargs):
        return JsonResponse({'status': 0, 'detail': ''})
